package pkg.andru.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * <br>
 * Id digest creator.</br>
 * 
 * @author idiottiger
 * 
 */
public class DigestUtils {

	public static final String LOG_TAG = "DigestUtils";

	private static MessageDigest md5Digest;

	private static MessageDigest shaDigest;

	private static final String MD5_AL = "MD5";

	private static final String SHA_AL = "SHA-1";

	private DigestUtils() {
		try {
			md5Digest = MessageDigest.getInstance(MD5_AL);
			shaDigest = MessageDigest.getInstance(SHA_AL);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}

	private static void initDigests() {
		if (md5Digest == null || shaDigest == null) {
			new DigestUtils();
		}
	}

	private static String calHex(MessageDigest md, String str) {
		byte[] digest = md.digest(str.getBytes());
		StringBuffer hexString = new StringBuffer();
		for (int i = 0; i < digest.length; i++) {
			String hex = Integer.toHexString(0xFF & digest[i]);
			if (hex.length() == 1) {
				hexString.append('0');
			}
			hexString.append(hex);
		}
		return hexString.toString();
	}

	/**
	 * create md5
	 * 
	 * @param str
	 * @return
	 */
	public static String md5Hex(String str) {
		initDigests();
		if (str == null || str.trim().length() == 0) {
			Log.e(LOG_TAG, "string need create MD5 is null");
			return null;
		}
		return calHex(md5Digest, str);
	}

	/**
	 * create sha
	 * 
	 * @param str
	 * @return
	 */
	public static String shaHex(String str) {
		initDigests();
		if (str == null || str.trim().length() == 0) {
			Log.e(LOG_TAG, "string need create SHA is null");
			return null;
		}
		return calHex(shaDigest, str);
	}

}
